package com.xbongbong.saas.model.impl;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.companyconfig.pojo.vo.CompanyConfigHasBeenEnableVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.dao.ContractPerformanceDao;
import com.xbongbong.saas.domain.entity.ContractPerformanceEntity;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.model.ContractPerformanceModel;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author long.rao
 * @version v1.0
 * @date 2019/2/25 15:57
 * @since v1.0
 */
@Service("contractPerformanceModel")
public class ContractPerformanceModelImpl implements ContractPerformanceModel {
    @Resource
    private ContractPerformanceDao contractPerformanceDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private CompanyConfigModel companyConfigModel;


    @Override
    public Integer insert(ContractPerformanceEntity entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        Integer success = contractPerformanceDao.insert(entity);

        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferContractPerformanceToFormData(entity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE);
        paasEsModel.insert(insertDTO);
        return success;
    }

    @Override
    public Integer update(ContractPerformanceEntity entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        Integer success = contractPerformanceDao.update(entity);

        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferContractPerformanceToFormData(entity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE);
        paasEsModel.update(insertDTO);
        return success;
    }

    @Override
    public List<ContractPerformanceEntity> findEntitys(Map<String, Object> param) {
        return contractPerformanceDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return contractPerformanceDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public ContractPerformanceEntity getByKey(Long key, String corpid) {
        return contractPerformanceDao.getByKey(key, corpid);
    }

    @Override
    public Integer save(ContractPerformanceEntity contractPerformanceEntity) throws XbbException {
        if (contractPerformanceEntity.getId() == null || Objects.equals(contractPerformanceEntity.getId(), 0L)) {
            contractPerformanceEntity.setId(null);
            return insert(contractPerformanceEntity);
        }
        return update(contractPerformanceEntity);
    }

    @Override
    public Integer deleteByKey(Long id, String corpid) throws XbbException{
        ContractPerformanceEntity entity = contractPerformanceDao.getByKey(id,corpid);
        Integer integer = contractPerformanceDao.deleteByKey(id, corpid);
//        DeleteDTO deleteDTO = new DeleteDTO();
//        deleteDTO.setEsId(corpid+"_"+ id);
//        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE);
//        paasEsModel.delete(deleteDTO);
        paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE,entity.getContractId());
        return integer;
    }

    @Override
    public Integer deleteBatch(List<Long> idIn, String corpid, Long dataId) throws XbbException{
        Integer integer = contractPerformanceDao.deleteBatch(idIn, corpid);
        List<InsertDTO> insertList = new ArrayList<>();
        for (Long item : idIn) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE.getType() + "_" + corpid + "_" + item);
            insertDTO.setParent(corpid + "_" + dataId);
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(ParameterConstant.DEL, DelEnum.DELETE.getDel());
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList);
        return integer;
    }

    @Override
    public Integer setDelByContractId(Long contractId, String corpid, Integer del, List<ContractPerformanceEntity> updateDelList) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put("contractId", contractId);
        param.put(ParameterConstant.DEL, DelEnum.APPROVE_STATUS.getDel());
        List<ContractPerformanceEntity> performanceEntityList = findEntitys(param);
        if (!performanceEntityList.isEmpty()) {
            updateDelList.addAll(performanceEntityList);
            List<Long> idIn = new ArrayList<>();
            performanceEntityList.forEach(item -> idIn.add(item.getId()));
            contractPerformanceDao.setDelByIdIn(idIn, corpid, del);
            long now = DateTimeUtil.getInt();
            List<InsertDTO> updateList = new ArrayList<>();
            getUpdateList(performanceEntityList, now, updateList, del);
            paasEsModel.updateBatch(updateList);
        }
        return null;
    }

    @Override
    public Integer setApprovalByContractId(Long contractId, String corpid, Integer del, List<ContractPerformanceEntity> updateDelList) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put("contractId", contractId);
        // 30365 【成功部】首页的合同订单金额与合同列表下的金额不一致;29113 【成功部】首页简报看板合同金额总计错误
        param.put("delIn", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_STATUS.getDel()));
        List<ContractPerformanceEntity> performanceEntityList = findEntitys(param);
        if (!performanceEntityList.isEmpty()) {
            updateDelList.addAll(performanceEntityList);
            List<Long> idIn = new ArrayList<>();
            performanceEntityList.forEach(item -> idIn.add(item.getId()));
            contractPerformanceDao.setDelByIdIn(idIn, corpid, del);
            long now = DateTimeUtil.getInt();
            List<InsertDTO> updateList = new ArrayList<>();
            getUpdateList(performanceEntityList, now, updateList, del);
            paasEsModel.updateBatch(updateList);
        }
        return null;
    }

    private void getUpdateList(List<ContractPerformanceEntity> performanceEntityList, long now, List<InsertDTO> updateList, Integer del) throws XbbException {
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractPerformanceToFormDataList(performanceEntityList);
        for (PaasFormDataEntity entity : paasFormDataEntities) {
            entity.setDel(del);
            entity.setUpdateTime(now);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE);
            updateList.add(insertDTO);
        }
    }

    @Override
    public Integer deleteByContractIdIn(List<Long> contractIdIn, String corpid) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put("contractIdIn", contractIdIn);
        param.put("delIn", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_STATUS.getDel()));
        List<ContractPerformanceEntity> performanceEntityList = findEntitys(param);
        if (!performanceEntityList.isEmpty()) {
            List<Long> idIn = new ArrayList<>();
            performanceEntityList.forEach(item -> idIn.add(item.getId()));
            contractPerformanceDao.deleteBatch(idIn, corpid);
            long now = DateTimeUtil.getInt();
            List<InsertDTO> updateList = new ArrayList<>();
            getUpdateList(performanceEntityList, now, updateList, DelEnum.DELETE.getDel());
            paasEsModel.updateBatch(updateList);
        }
        return null;
    }

    @Override
    public void insertBatch(List<ContractPerformanceEntity> insertBatchList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        if(CollectionsUtil.isEmpty(insertBatchList)){
            return;
        }
        contractPerformanceDao.insertBatch(insertBatchList);

        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractPerformanceToFormDataList(insertBatchList);
        List<InsertDTO> insertDTOList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntity entity : paasFormDataEntities) {
            long now = DateTimeUtil.getInt();
            entity.setAddTime(now);
            entity.setUpdateTime(now);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.insertBatch(insertDTOList,refreshPolicy);
    }

    @Override
    public void reductionEsInUpdate(List<ContractPerformanceEntity> performanceEntityList) throws XbbException {
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractPerformanceToFormDataList(performanceEntityList);
        List<InsertDTO> insertDTOList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntity entity : paasFormDataEntities) {
            InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
    }

    @Override
    public Boolean openDistribution(String corpid) throws XbbException {

        Integer enable = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.CONTRACT_PERFORMANCE_RULE_SET.getAlias());
        return Objects.equals(enable, BasicConstant.IS_USE);
    }

    @Override
    public List<Long> getDirtyDataContractIds(String corpid) throws XbbException {
        return contractPerformanceDao.getDirtyDataContractIds(corpid);
    }

    @Override
    public Integer updateBatch(List<ContractPerformanceEntity> list, String corpid) throws XbbException {
        contractPerformanceDao.updateBatch(list, corpid);

        long now = DateTimeUtil.getInt();
        List<InsertDTO> updateList = new ArrayList<>();
        getUpdateList(list, now, updateList, DelEnum.NORMAL.getDel());
        paasEsModel.updateBatch(updateList);

        return null;
    }
}
